package Controller

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"server/Service"
	"time"
)

func SetupExcelRouter(r *gin.Engine) {
	Service.SetupExcelCommandHandler()
	router := r.Group("/excel")
	ExcelWebSocket(router)
}

var upGrader = websocket.Upgrader{
	HandshakeTimeout: time.Second * 30,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func ExcelWebSocket(r *gin.RouterGroup) {
	r.GET("/ws", func(context *gin.Context) {
		ws, err := upGrader.Upgrade(context.Writer, context.Request, nil)
		if err != nil {
			return
		}

		defer func() {
			_ = ws.Close()
		}()

		for {
			messageType, message, err := ws.ReadMessage()
			if err != nil {
				fmt.Println(err)
				return
			}

			var command Service.ExcelCommand
			err = json.Unmarshal(message, &command)

			if err != nil {
				if string(message) == "ping" {
					message = []byte("pong")
				}
				fmt.Println(string(message))
				err = ws.WriteMessage(messageType, message)
			} else {
				fmt.Printf("%+v\n", command)
				Service.ExcelCommandProcess(ws, command)
			}

			if err != nil {
				fmt.Println(err)
				break
			}
		}
	})
}
